package com.qianbao.qianbaobusiness.ui.cashier.databill;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;

import com.qianbao.qianbaobusiness.R;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


public abstract class BaseCommActivity extends RxAppCompatActivity implements OnClickListener {
    public static final int LOGOUT_CALLBACK_TAG = 999;// 登录超时回调
    private InputMethodManager manager;

    private OnLogoutState mListener;
    public boolean isFullscreen    = false;
    public boolean isWebFullscreen = false;

    public int mPost = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置activity背景
        this.getWindow().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.app_white)));
        ActionBar actionbar = getActionBar();
        if (actionbar != null) {
            actionbar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.app_white)));
            actionbar.setDisplayHomeAsUpEnabled(true);// 是否显示返回
            actionbar.setHomeButtonEnabled(true);// 返回是否可点击
            actionbar.setDisplayShowHomeEnabled(false);// 不显示icon
        }
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        init();
        setTranslucentStatus();
    }

    protected abstract void init();

    /**
     * 当某个activity变得“容易”被系统销毁时，该activity的onSaveInstanceState就会被执行，
     * 除非该activity是被用户主动销毁的，例如当用户按BACK键的时候
     * 一个原则：即当系统“未经你许可”时销毁了你的activity，则onSaveInstanceState会被系统调用 情景： 1.
     * 当用户按下HOME键时 2. 长按HOME键，选择运行其他的程序时。 3. 按下电源按键（关闭屏幕显示）时。 4. 从activity
     * A中启动一个新的activity时。 5. 屏幕方向切换时，例如从竖屏切换到横屏时。 以上情景触发该函数，并且开发者可以保存一些数据状态
     */
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
    }

    /**
     * onSaveInstanceState方法和onRestoreInstanceState方法“不一定”是成对的被调用的，
     * onRestoreInstanceState被调用的前提是， activity A“确实”被系统销毁了，而如果仅仅是停留在有这种可能性的情况下，
     * 则该方法不会被调用，例如，当正在显示activity A的时候，用户按下HOME键回到主界面， 然后用户紧接着又返回到activity
     * A，这种情况下activity A一般不会因为内存的原因被系统销毁， 故activity
     * A的onRestoreInstanceState方法不会被执行
     */
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
    }

    @Override
    protected void onResume() {
        mPost = 0;
        /* 友盟统计 */
        //        if (!UIApplication.isDevelop) {
        //        JPushInterface.onResume(this);
        //        long time1 = System.currentTimeMillis();
        //        if (MyApp.getInstance().currentTime != 0 && (time1 - MyApp.getInstance().currentTime > 60000)) {// 10分钟没有任何操作，判定超时
        //            if (mListener != null) {
        //                mListener.onLogout();
        //            }
        //            LogUtil.d("您已有10分钟未进行任何操作，系统判定超时！");
        //        } else {
        //            // 未超时，则重置超时时间为0
        //            MyApp.getInstance().currentTime = 0;
        //        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        /* 友盟统计 */
        //        if (!UIApplication.isDevelop) {
        //        JPushInterface.onPause(this);
        closeLoadingDialog();
        super.onPause();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void setOnLogoutState(OnLogoutState listener) {
        mListener = listener;
    }

    public abstract interface OnLogoutState {
        public void onLogout();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            /* 键盘不弹出 */
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                inputComplete();
            }
        }
        return super.onTouchEvent(event);
    }

    public void inputComplete() {

    }

    @Override
    public void onDestroy() {
        System.gc();
        //        OkHttpClientManager.cancelAll(getCN());
        super.onDestroy();
    }

    public abstract String getCN();

    /* 数组转map */
    public static Map<String, Object> convertBeanToMap(Object bean) throws IllegalArgumentException, IllegalAccessException {
        Field[] fields = bean.getClass().getDeclaredFields();
        HashMap<String, Object> data = new HashMap<String, Object>();
        for (Field field : fields) {
            field.setAccessible(true);
            data.put(field.getName(), field.get(bean));
        }
        return data;
    }

    /**
     * 重新登录
     */
    public void reLogin() {

    }

    /* 返回首页 */
    @SuppressLint("NewApi")
    public void backToMain() {
        // UIApplication.backToMain = true;
        Intent upIntent = NavUtils.getParentActivityIntent(this);
        if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
            TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
        } else {
            upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            NavUtils.navigateUpTo(this, upIntent);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LOGOUT_CALLBACK_TAG) {
            //            LogoutCallback(UIApplication.isLogin);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public abstract void LogoutCallback(boolean islogin);

    @Override
    public void onClick(View v) {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
            lastClickTime = currentTime;
            onCritClick(v);
        } else {
            //			ToastManager.show(this, "不可连续点击");
        }
    }

    public abstract void onCritClick(View v);

    /**
     * 判断是否双击
     */
    public static final int  MIN_CLICK_DELAY_TIME = 500;
    private             long lastClickTime        = 0;

    public boolean isFastDoubleClick() {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
            lastClickTime = currentTime;
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onTrimMemory(int level) {
        switch (level) {
            case TRIM_MEMORY_UI_HIDDEN:
                break;
        }
        super.onTrimMemory(level);
    }

    public Context getThis() {
        return this;
    }

    public int statusBarHeight;

    /**
     * 设置状态栏背景状态
     */
    @SuppressLint("ResourceAsColor")
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void setTranslucentStatus() {
        //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        //
        //            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 所有界面设为竖屏
        //            SystemStatusManager tintManager = new SystemStatusManager(this);
        //            tintManager.setStatusBarTintEnabled(true);
        //
        //            if (isWebFullscreen) {
        //                tintManager.setStatusBarTintResource(R.color.c_3F454F);// 状态栏灰色背景
        //            } else {
        //                if (!isFullscreen) {
        //                    tintManager.setStatusBarTintResource(R.color.color_red);// 状态栏红色背景
        //                } else {
        //                    tintManager.setStatusBarTintResource(R.color.color_white);// 状态栏白色背景
        //                }
        //            }
        //            statusBarHeight = tintManager.getConfig().getStatusBarHeight();
        //
        //            int statusBarHeights = Tools.getStatusBarHeight(this);
        //        }
    }

    /**
     * 配合状态栏一体化使用，以4.4为分隔线判断是否需要隐藏多加的view
     */
    public void setStatusBar(View v) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, statusBarHeight);
            v.setLayoutParams(params);
            v.setVisibility(View.VISIBLE);
        } else {
            v.setVisibility(View.GONE);
        }
    }

    public void showLoadingDialog() {
        //        自V2.0.0开始去除转菊花图
        //        if (loadingDialog == null) {
        //            loadingDialog = new LoadingDialog(getThis()); // 初始化进度条
        //        }
        //        if (!loadingDialog.isShowing()) {
        //            loadingDialog.show();
        //        }
    }

    public void closeLoadingDialog() {
        //        if (loadingDialog != null && mPost == 0) {
        //            if (loadingDialog.isShowing()) {
        //                loadingDialog.cancel();
        //            }
        //            loadingDialog = null;
        //        }
    }
}